package com.zh.modules.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.common.annotation.Limit;
import com.zh.common.vo.Result;
import com.zh.modules.app.entity.UserDO;
import com.zh.modules.app.entity.vo.UserVO;
import com.zh.modules.app.param.LoginParam;
import com.zh.modules.app.param.RegisterParam;
import com.zh.modules.app.param.SendCodeForm;
import com.zh.modules.app.repository.UserRepository;
import com.zh.modules.app.service.UserService;
import com.zh.modules.app.utils.ConvertUtils;
import com.zh.modules.app.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/app/user")
@Api(tags = "PC端——用户登录")
@Slf4j
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Autowired
    JavaMailSenderImpl mailSender;

    @Value("${ipmarket.email.send}")
    private String send;

    @GetMapping("/getUser")
    @ApiOperation("获取当前登录用户")
    public Result<UserVO> getUser() {
        UserDO userDO = JwtUtils.getUser();
        if(userDO==null){
            return Result.failed("No Login");
        }
        UserVO userVO = ConvertUtils.copyObject(userDO, UserVO.class);
        return Result.succeed(userVO);
    }

    @PostMapping("/login")
    @ApiOperation("账户密码登录")
    public Result login(@RequestBody LoginParam loginParam) {
        UserDO userDO = userRepository.getOne(new LambdaQueryWrapper<UserDO>().eq(UserDO::getUsername, loginParam.getUsername()));
        if (userDO == null) {
            return Result.failed("The user does not exist", "用户不存在", null);
        }
        if (!loginParam.getPassword().equals(userDO.getPassword())) {
            return Result.failed("Account or password incorrect", "账号或密码错误", null);
        }
        //生成token
        String token = JwtUtils.generateToken(userDO);
        return Result.succeed(token);
    }

    @GetMapping("/logout")
    @ApiOperation("登出")
    public Result logout(HttpServletResponse response) {
        return Result.succeed();
    }

    /**
     * 发送邮箱登录验证码
     */
    @Limit(count = 10)
    @PostMapping("/sendEmailCode")
    @ApiOperation("发送邮箱登录验证码")
    public Result sendEmailCode(@RequestBody SendCodeForm request) {
        try {
            String code = userService.sendEmailCode(request);
            SimpleMailMessage mailMessage = new SimpleMailMessage();//创建一个简单的邮件信息对象
            //设置邮件发送信息的内容
            mailMessage.setSubject("Verification Code");//标题
            mailMessage.setText("Dear user,\n\n" + "You are verifying your email address. Please use the following verification code to complete the process:\n\n" + "<span style='font-size: 20px;font-weight: bold;'>Verification code: " + code + "</span>\n" + "Validity period: 5 minutes\n\n" + "Do not share this code with anyone else. If you did not request this verification, please ignore this email.\n\n" + "Thank you for using our service!");
            mailMessage.setFrom(send);//内容为发送方的邮箱地址
            mailMessage.setTo(request.getEmail());//内容为接收方邮箱地址
            mailSender.send(mailMessage);//发送邮件
            return Result.succeed("发送成功,注意查收");
        } catch (Exception e) {
            log.error("sendEmailCode", e);
            return Result.failed("Failed to send email. Please check if the email is correct", "邮箱发送失败，请检查邮箱是否正确！", null);
        }
    }


    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody RegisterParam registerParam) {
        Boolean flag = userService.checkEmailCode(registerParam);
        if (!flag) {
            return Result.failed("Invalid verification code!", "验证码错误！", null);
        }

        String userName = registerParam.getUsername();
        UserDO userDO = userRepository.getOne(new LambdaQueryWrapper<UserDO>().eq(UserDO::getUsername, userName));
        if (userDO != null) {
            return Result.failed("The email has already been registered!", "该邮箱已被注册！", null);
        }
        UserDO newUser = new UserDO();
        newUser.setUsername(registerParam.getUsername());
        newUser.setEmail(registerParam.getUsername());
        newUser.setPassword(registerParam.getPassword());
        boolean save = userRepository.save(newUser);
        if (!save) {
            return Result.failed("Unknown exception");
        }
        return Result.succeed();
    }

    @PostMapping("/forgetPassword")
    @ApiOperation("忘记密码")
    public Result<Boolean> forgetPassword(@RequestBody RegisterParam registerParam) {
        Boolean flag = userService.checkEmailCode(registerParam);
        if (!flag) {
            return Result.failed("Invalid verification code!", "验证码错误！", null);
        }
        String userName = registerParam.getUsername();
        UserDO userDO = userRepository.getOne(new LambdaQueryWrapper<UserDO>().eq(UserDO::getUsername, userName));
        if (userDO == null) {
            return Result.failed("The email is not registered!", "该邮箱未注册！", null);
        }
        userDO.setPassword(registerParam.getPassword());
        userRepository.updateById(userDO);
        return Result.succeed(true);
    }
}
